<?
    class Principio_Model_CompanyMapper extends Principio_Library_Mapper
    {
        const TYPE_POOL = 1;
        const TYPE_COMPANY = 2;
        const TYPE_COMPANY_NOT_IN_POOL = 3;
        const TYPE_ALL = 4;
        const TYPE_NOT_POOL_NOT_IN_POOL = 5;

        private static $type_str = array(self::TYPE_POOL => "=2", self::TYPE_COMPANY => "<>2", self::TYPE_COMPANY_NOT_IN_POOL => "<>3", self::TYPE_ALL => ">0", self::TYPE_NOT_POOL_NOT_IN_POOL => "=1");

        private static $db_table = null;

        private static function getDBTable()
        {
            if (self::$db_table == null)
                self::$db_table = new Principio_Model_DbTable_Company();

            return self::$db_table;
        }


        private static function doDelete($company_id)
        {

            // This will delete ALL SPA, accountlink, spa_ext_template and company_type_ext_template
            Principio_Model_SpaMapper::deleteAllInCompany($company_id);

            // Delete all accounts
            Principio_Model_AccountMapper::deleteAll($company_id);

            // Delete SPA
            self::getDBTable()->delete(array("id=?" => $company_id));
        }


        public static function delete(Principio_Model_Company $model_company, $use_transaction = true)
        {
            try
            {
                if ($use_transaction)
                    self::getDBTable()->getAdapter()->beginTransaction();

                if ($model_company->isPool())
                {
                    foreach (Principio_Model_CompanyMapper::getAncestors($model_company->getId()) as $model_company2)
                        self::doDelete($model_company2->getID());
                };

                self::doDelete($model_company->getID());

                if ($use_transaction)
                    self::getDBTable()->getAdapter()->commit();

                return true;
            }
            catch (Exception $ex)
            {
                $return = self::reportException($ex);

                if ($use_transaction)
                {
                    self::getDBTable()->getAdapter()->rollback();
                    return false;
                }
                else
                    return $return;

            };
        }


        public static function checkUniqueLogin(&$values)
        {
            try
            {
                $select = self::getDBTable()->select(Zend_Db_Table_Abstract::SELECT_WITH_FROM_PART)->where("login=?", $values['login'])->where("company_id=?", $values['company_id'])->where("id<>?", $values['id'])->columns("id");
                return (is_null(self::getDBTable()->fetchRow($select)));
            }
            catch (Exception $ex)
            {
                return self::reportException($ex);
            };
        }

        public static function save(Principio_Model_Company &$model_company)
        {
            try
            {
                $data = array(
                            "caption" => $model_company->getCaption(),
                            "proxy" => $model_company->getProxy(),
                            "global_template" => $model_company->getGlobalTemplate(),
                            "ext_template" => $model_company->getExtTemplate(),
                            "vlan" => $model_company->getVlanId(),
                            "vlan_pc" => $model_company->getVlanPcId(),
                            "default_gw" => $model_company->getDefaultGw(),
                            "netname" => $model_company->getNetname(),
                            "netmask" => $model_company->getNetmask(),
                            "broadcast" => $model_company->getBroadcast(),
                            "range_from" => $model_company->getRangeFrom(),
                            "range_to" => $model_company->getRangeTo(),
                            "ip" => $model_company->getIp(),
                            "pool_id" => $model_company->getOwnerPoolId(),
                            "type" => $model_company->getType()
                );

                if ($model_company->getID() == -1)
                    return self::getDBTable()->insert($data);
                else
                    return self::getDBTable()->update($data, array("id=?" => $model_company->getID()));
            }
            catch (Exception $ex)
            {
                return self::reportException($ex);
            };
        }

        public static function get($id = null)
        {
            try
            {
                if (is_null($id))
                {
                    $companies_raw = self::getDBTable()->fetchAll();
                    $companies = array();
                    foreach ($companies_raw as $company)
                        $companies[$company->id] = new Principio_Model_Company($company->toArray());

                    return $companies;
                }
                else
                {
                    $company_raw = self::getDBTable()->find(intval($id));
                    return (is_null($company_raw) ? new Principio_Model_Company() : new Principio_Model_Company($company_raw[0]->toArray()));
                };
            }
            catch (Exception $ex)
            {
                return self::reportException($ex);
            };
        }

        public static function getByType($type)
        {
            try
            {
                $select = self::getDBTable()->select()->order(array("type DESC", "caption DESC"))->where("type".self::$type_str[$type]);
                $companies_raw = self::getDBTable()->fetchAll($select);
                $companies = array();
                foreach ($companies_raw as $company)
                    $companies[$company->id] = new Principio_Model_Company($company->toArray());

                return $companies;
            }
            catch (Exception $ex)
            {
                return self::reportException($ex);
            };
        }


        public static function getSpaByType($company_id, $type_id)
        {
            try
            {
                $db_table = new Principio_Model_DbTable_Spa();
                $select = $db_table->select()->where("company_id=?", $company_id)->where("type_id=?", $type_id);
                $spaes_raw = $db_table->fetchAll($select);
                $spaes = array();
                foreach ($spaes_raw as $spa)
                    $spaes[$spa->id] = Principio_Model_SpaMapper::get($spa->id);

                return $spaes;
            }
            catch (Exception $ex)
            {
                return self::reportException($ex);
            };
        }

        public static function getAncestors($id)
        {
            try
            {
                $select = self::getDBTable()->select()->where("pool_id=?", $id);
                $ancestors_raw = self::getDBTable()->fetchAll($select);
                $ancestors = array();
                foreach ($ancestors_raw as $ancestor)
                    $ancestors[$ancestor->id] = new Principio_Model_Company($ancestor->toArray());

                return $ancestors;
            }
            catch (Exception $ex)
            {
                return self::reportException($ex);
            };
        }


        public static function getAncestorsCount($id)
        {
            $select = self::getDBTable()->select()->from(self::getDBTable(), "COUNT(*) as num")->where("type=3")->where("pool_id=?", $id);
            $result = self::getDBTable()->fetchAll($select);
            return (is_null($result) ? 0 : (intval($result[0]->num)));
        }


        public static function getIPRanges2($company_id)
        {
            try
            {
                $select = self::getDBTable()->select()->where("type<>3")->where("id<>?", $company_id);
                $result = self::getDBTable()->fetchAll($select);

                $companies = array();
                foreach ($result as $company)
                    $companies[] = new Principio_Model_Company($company->toArray());

                return $companies;
            }
            catch (Exception $ex)
            {
                return self::reportException($ex);
            };
        }

        public static function checkUniqueCaption(Principio_Model_Company $model_company)
        {
            try
            {
                $select = self::getDBTable()->select("id")->where("caption=?", $model_company->getCaption())->where("id<>?", $model_company->getID());
                return (count(self::getDBTable()->fetchAll($select)) == 0);
            }
            catch (Exception $ex)
            {
                return self::reportException($ex);
            };
        }


        public static function updateTemplates($company_id, &$global_template, &$ext_template)
        {
            try
            {
                $data = (array("global_template" => $global_template, "ext_template" => $ext_template));
                return self::getDBTable()->update($data, array("id=?" => $company_id));
            }
            catch (Exception $ex)
            {
                return self::reportException($ex);
            };
        }

        public static function search($string)
        {
            $search_fields = array(
                "caption" => "Caption",
                "proxy" => "Proxy",
                "global_template" => "Global Template",
                "ext_template" => "Ext template",
                "vlan" => "Vlan",
                "vlan_pc" => "Vlan pc",
                "default_gw" => "Default GW",
                "netname" => "Netname",
                "netmask" => "Netmask",
                "broadcast" => "Broadcast",
                "range_from" => "Range from",
                "range_to" => "Range to",
                "pool_id" => "pool id",
                "type" => "Type"
            );
            $result = parent::searchInDB(self::getDBTable(), $search_fields, $string);
            foreach ($result as $res)
            {
                $model_search = new Principio_Model_Search($string, "Companies");
                $model_search->setId($res["id"])->setResultName($res["caption"])->setOpenItemFunctionName("Company");
                foreach ($res as $col_name => $value)
                {
                    if (strstr($value, $string) && in_array($col_name, array_keys($search_fields)))
                        $searchable_text[$search_fields[$col_name]] = $value;
                }
                $model_search->setResult($searchable_text);
                $search[$res["id"]] = $model_search;
            }
            return $search;
        }
    }
?>